import { Key, forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Space, Transfer, TransferProps } from 'antd';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  proShiftTeamUserPage,
  proShiftTeamUserSave
} from '@/services/bizApi/shengchanbanzurenyuanjiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type PersonalRef = {
  open: (
    arg: EditOpenBaseArgs & {
      rowData: BizObject;
    }
  ) => void;
};

export type EditProps = {};

const Personal: React.ForwardRefRenderFunction<PersonalRef, EditProps> = (_, ref) => {
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<PersonalRef['open']>[0]>();
  const [targetKeys, setTargetKeys] = useState<TransferProps['targetKeys']>([]);
  const [selectedKeys, setSelectedKeys] = useState<TransferProps['targetKeys']>([]);

  const proShiftTeamUser = useRequest(
    async (id: number) => {
      const res = await proShiftTeamUserPage({
        teamId: id,
        page: 1,
        size: 1000
      });
      setTargetKeys((res?.data?.records?.map((item) => item?.userId) as unknown as Key[]) || []);
    },
    {
      manual: true
    }
  );

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records?.map((item) => {
        return {
          key: item?.id,
          title: item?.fullName,
          description: item?.fullName
        };
      });
    },
    {
      refreshDeps: []
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          proShiftTeamUser.run(arg?.rowData?.id as unknown as number);
        });
      }
    };
  });

  const onCancel = () => {
    // if (submit.loading) {
    //   store.app?.message.info('正在提交中，请稍后');

    //   return;
    // }

    setOpen(false);
    setSelectedKeys([]);
  };

  // 仅保存
  const onSave = async () => {
    const userNameList = targetKeys?.map((item) => {
      const name = userInfo?.data?.filter((itm) => itm.key === item)?.[0]?.title;
      return name || '';
    });
    const query = {
      teamId: args?.rowData?.id,
      userIdList: targetKeys,
      userNameList
    } as BIZAPI.ProShiftTeamUserCreateReq;
    await proShiftTeamUserSave(query);

    args?.onSuccess?.();
    setOpen(false);
    setSelectedKeys([]);

    store.app?.message.success('操作成功');
  };

  const onChange: TransferProps['onChange'] = (nextTargetKeys, direction, moveKeys) => {
    console.log('targetKeys:', nextTargetKeys);
    console.log('direction:', direction);
    console.log('moveKeys:', moveKeys);
    setTargetKeys(nextTargetKeys);
  };

  const onSelectChange: TransferProps['onSelectChange'] = (
    sourceSelectedKeys,
    targetSelectedKeys
  ) => {
    console.log('sourceSelectedKeys:', sourceSelectedKeys);
    console.log('targetSelectedKeys:', targetSelectedKeys);
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  const onScroll: TransferProps['onScroll'] = (direction, e) => {
    console.log('direction:', direction);
    console.log('target:', e.target);
  };

  return (
    <Drawer
      title="班组成员"
      extra={
        <Space>
          <Button type="primary" onClick={onSave}>
            保存
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Transfer
        dataSource={userInfo?.data}
        showSearch
        titles={['未选', '已选']}
        targetKeys={targetKeys}
        selectedKeys={selectedKeys}
        onChange={onChange}
        onSelectChange={onSelectChange}
        onScroll={onScroll}
        render={(item) => item.title || ''}
        listStyle={{
          width: '100%',
          height: '600px'
        }}
      />
    </Drawer>
  );
};

export default forwardRef(Personal);
